// Package middleware 文件上传模块
package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"mime/multipart"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"time"
)

type UploadMiddleWare struct {
	FileExt  string
	FileSize int64
}

// New 构造默认值
func (middleware *UploadMiddleWare) New() *UploadMiddleWare {
	if middleware.FileExt == "" {
		middleware.FileExt = "gif|png|jpg|jpeg" //上传格式
	}
	if middleware.FileSize == 0 {
		middleware.FileSize = 1024 * 1024 * 1 //1MB
	}
	return middleware
}

// Upload 上传
func (middleware *UploadMiddleWare) Upload(ctx *gin.Context, file *multipart.FileHeader, path string) (int, string) {
	ok, fileType := middleware.IsImgFormat(file.Filename)
	if !ok {
		return 1, "图片格式错误"
	}
	if file.Size > middleware.FileSize {
		return 1, "图片太大拉"
	}
	filename := filepath.Join(GenerateFileName() + fileType)
	folderPath := filepath.Join("uploads/" + path + "/" + filename)
	os.Mkdir("uploads/"+path+"/", 0755)
	err := ctx.SaveUploadedFile(file, folderPath)
	if err != nil {
		return 1, "图片保存失败"
	}
	url := strings.Replace("/"+folderPath, "\\", "/", -1)
	return 0, url
}

// IsImgFormat 判断是否是图片格式
func (middleware *UploadMiddleWare) IsImgFormat(filename string) (bool, string) {
	fileDot := strings.LastIndex(filename, ".")
	if fileDot == -1 {
		return false, ""
	}
	fileType := strings.ToLower(filename[fileDot:])
	if middleware.FileExt == "all" {
		return true, fileType
	}
	format := `^(\.(` + middleware.FileExt + `))$`
	ok, _ := regexp.MatchString(format, fileType)
	return ok, fileType
}

// GenerateFileName 随机文件名
func GenerateFileName() string {
	date := time.Now().Format("20060102")
	r := rand.Intn(10000)
	code := fmt.Sprintf("%s%d%04d", date, time.Now().UnixNano()/1e6, r)
	return code
}
